package com.freedom.web.mymvc.handler;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.web.mymvc.pool.ExecutorPool;
import com.freedom.web.mymvc.pool.MyMVCRunnable;
import com.freedom.web.mymvc.utils.LoggerUtils;
import com.freedom.web.mymvc.utils.NettyUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;

public class HttpUserHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
	// logger
	private static final Logger logger = LogManager.getLogger(HttpUserHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
		//
		LoggerUtils.debug(logger, "enter channelRead0");
		// 1)保证解析结果正确,否则一切无从谈起
		if (!request.getDecoderResult().isSuccess()) {
			NettyUtils.sendError(ctx, BAD_REQUEST);
			return;
		}
		// 2)确保方法是我们需要的(目前只支持GET | POST | PUT | HEAD ,其它不支持)
		if (request.getMethod() != GET && request.getMethod() != POST//
				&& request.getMethod() != PUT && request.getMethod() != HEAD) {
			NettyUtils.sendError(ctx, METHOD_NOT_ALLOWED);
			return;
		}
		// 3)uri是有长度的
		final String uri = request.getUri();
		if (uri == null || uri.trim().length() == 0) {
			NettyUtils.sendError(ctx, FORBIDDEN);
			return;
		}

		// 4)一切就绪，准备抛给线程池
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		MyMVCRunnable runnable = new MyMVCRunnable(ctx, request, response);
		ExecutorPool.getInstance().execute(runnable);
		//
		// 其它的就交给线程池了 :)
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		LoggerUtils.error(logger, cause.toString());
		ctx.close();
	}

}
